package com.superiron.scaffold.security.service;

import cn.hutool.core.bean.BeanUtil;
import com.superiron.scaffold.entity.RoleEntity;
import com.superiron.scaffold.entity.UserEntity;
import com.superiron.scaffold.security.detail.IotGlobalRole;
import com.superiron.scaffold.security.detail.IotGlobalUser;
import com.superiron.scaffold.service.UserRoleService;
import com.superiron.scaffold.service.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 获取登录用户信息
 *
 * @author yzg
 * @date 2022年6月20日10:52:10
 * 版权所有 泰山信息科技有限公司
 */
@Service
public class GlobalUserDetailsService implements UserDetailsService {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserRoleService userRoleService;
	
	@Override
	@Transactional
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		
		List<UserEntity> userEntityList = userService.findAllByMobile(userName);
		
		if (CollectionUtils.isNotEmpty(userEntityList)) {
			List<RoleEntity> userRoles = userRoleService.queryUserRole(userEntityList.get(0).getId());
			List<IotGlobalRole> iotGlabolRoles = Optional.ofNullable(userRoles).get().stream().map(entity -> BeanUtil.copyProperties(entity, IotGlobalRole.class)).collect(Collectors.toList());
			return new IotGlobalUser(userEntityList.get(0), iotGlabolRoles);
		} else {
			throw new UsernameNotFoundException("用户不存在");
		}
	}
}
